# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import akshare as ak

import xlsxwriter

from flask import Flask, jsonify, request, abort, make_response

import jwt

import datetime

from functools import wraps


import os

import openpyxl

import cfg

import configparser

import json

import pymongo

import requests


from openpyxl.styles import numbers

import schedule

import time

from mongo import MongoHelper # mongo 数据库连接池

# from tdengine import tdconnc

app = Flask(__name__)

# 这是一个示例密钥，实际应用中应该使用一个复杂且随机的密钥
app.config['SECRET_KEY'] = 'your_secret_key'
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            if auth_header.startswith('Bearer '):
                token = auth_header.split(" ")[1]  # 分割"Bearer "和token

        if not token:
            return jsonify({'message': 'Token is missing!'}), 403

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
        except:
            return jsonify({'message': 'Token is invalid!'}), 403

        return f(*args, **kwargs)

    return decorated

USERS = {
    'user1': 'pass1',
    'user2': 'pass2'
}
# 模拟的登录会话验证
def authenticate():
    auth = request.authorization
    if auth and auth.username in USERS and \
            USERS[auth.username] == auth.password:
        return True
    return False


# 鉴权装饰器
def requires_auth(f):
    def decorated(*args, **kwargs):
        if not authenticate():
            abort(401)
            return f(*args, **kwargs)

    return decorated


@app.route('/')
def index():
    return "Hello, World!"


@app.route('/unprotected')
def unprotected():
    return jsonify({'message': 'Anyone can view this!'})


@app.route('/protected')
@token_required
def protected():
    return jsonify({'message': 'This is only available for people with valid tokens.'})

@app.route('/login')
def login():
    auth = request.authorization
    if auth and auth.password == 'password':
        token = jwt.encode({
            'user': auth.username,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
        }, app.config['SECRET_KEY'])

        return jsonify({'token': token})

    return make_response('Could not verify!', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})

@app.route('/home')
@requires_auth
def index():
    return "Hello, World!"

def theJob():
    print("================================")

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.

def excel_add(filename,sheet,titles,contents):
    print(f'{filename}')
    if os.path.exists(filename):
        print(f"文件 {filename} 已存在")
        data = openpyxl.load_workbook(filename)
        if sheet in data.sheetnames:
            print(f"{sheet}存在")
        else:
            print(f"{sheet}不存在")
            data.create_sheet(sheet)
            table = data[sheet]
            for i,v in enumerate(titles):
                print(f"{v}")
                print(f"{i}")
                # cell = table.cell(row=1, column=i+1)
                # cell.number_format()
                cell = table.cell(row=1, column=i + 1)
                cell.number_format = "@"
                table.cell(1, i + 1, v)
            for ii, vv in enumerate(contents):
                for iii, vvv in enumerate(vv):
                    table.cell(2 + ii, iii + 1, vvv)
            # table.cell(2, 2, 'test')
            data.save(filename)
    else:
        print(f"文件 {filename} 不存在")
        data = openpyxl.Workbook()
        data.create_sheet(sheet)
        table = data[sheet]

        for i,v in enumerate(titles):
            print(f"{v}")
            print(f"{i}")
            cell = table.cell(row=1, column=i+1)
            cell.number_format="@"
            table.cell(1,i+1,v)
        for ii, vv in enumerate(contents):
            for iii, vvv in enumerate(vv):
                table.cell(2+ii,iii+1,vvv)

        # table.cell(1,1,'test')
        data.save(filename)

# 创建一个新的Excel文件并添加一个工作表
def create_excel(filename,sheets,titles,contents):
    if os.path.exists(filename):
        print(f"文件 {filename} 已存在")


    else:
        print(f"文件 {filename} 不存在")
    # 创建一个新的Excel文件
    workbook = xlsxwriter.Workbook(filename)


    for i, v in enumerate(sheets):
        # 添加一个名为'Sheet1'的工作表
        worksheet = workbook.add_worksheet(name=v)




    # 定义一些数据
    data = [
        ['姓名', '年龄', '职业'],
        ['Alice', 28, 'Engineer'],
        ['Bob', 22, 'Designer'],
        ['Charlie', 35, 'Manager']
    ]

    #

    # 在工作表中写入数据
    for row_num, row in enumerate(data):
        for col_num, item in enumerate(row):
            worksheet.write(row_num, col_num, item)

    # 关闭Excel文件
    workbook.close()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')

    schedule.every(5).seconds.do(theJob)
    username = 'sfin'
    password = 'qweasd1!'
    database_name = 'sfin'
    ml = pymongo.MongoClient(username=username,password=password, host='101.132.111.19',port=27017,authSource='sfin')
    db = ml.info_data
    print(db['equit_basic'])



    # 资金流入/流出 大宗交易 融资融卷 财务指标， 股东数量，基金持股，机构持股
    config = configparser.ConfigParser()
    config.read('config.cfg')
    symbol = config.get('code','symbol')
    market = config.get('code','market').split(',')
    name = config.get('code','name')

    # print(symbol.split(','))
    t = config.get('code','tuples')

    # print(t)
    dic = eval(t)
    # print(type(dic))
    names = name.split(',')
    for i,val in enumerate(symbol.split(',')):
        # uu
        print(val)
        # print(names[i])
        stock_individual_fund_flow_df = ak.stock_individual_fund_flow(stock=val, market=market[i])

        content = stock_individual_fund_flow_df.values.tolist()

        for ii,v in enumerate(content):
            # print(f"{v[0].replace('-','')}")
            d = v[0].replace('-','')
            # ak.stock_margin_ratio_pa('20231013') # 办公室网络不通
        # holding = ak.stock_institute_hold_detail(stock=val,quarter="20241")
        # print(f"{holding}")
        # dd = ak.stock_fund_stock_holder(symbol=val)
        # print(f"{dd}---")
        ak.stock_financial_analysis_indicator(symbol=val,start_year="2020")


        excel_add('test.xlsx', names[i], stock_individual_fund_flow_df.columns.tolist(),stock_individual_fund_flow_df.values.tolist())

    stock_zh_a_hist_df = ak.stock_zh_a_hist(
        symbol="600487",
        period="daily",
        start_date="20240401",
        end_date="20240419",
        adjust=""
    )
    # print(stock_zh_a_hist_df)

    # stock_individual_info_em_df = ak.stock_individual_info_em(symbol="600487")
    # print(stock_individual_info_em_df)

    # 个股资金流

    # stock_individual_fund_flow_df
    #print(stock_individual_fund_flow_df.head(0))
    #print(stock_individual_fund_flow_df.columns)
    # print(stock_individual_fund_flow_df.columns.tolist())

    #print(stock_individual_fund_flow_df.iloc[1])


    # stock_zh_a_gdhs_df = ak.stock_zh_a_gdhs(symbol="600487")
    # print(stock_zh_a_gdhs_df)

    # stock_margin_ratio_pa_df = ak.stock_margin_ratio_pa(date="20231013")
    # print(stock_margin_ratio_pa_df)

    #stock_margin_sse_df = ak.stock_margin_sse(start_date="20010106", end_date="20210208")
    # print(stock_margin_sse_df)

    # stock_zt_pool_em_df = ak.stock_zt_pool_em(date='20240419')
    # print(stock_zt_pool_em_df)

    # excel_add('test.xlsx','sheet1',stock_individual_fund_flow_df.columns.tolist(),stock_individual_fund_flow_df.values.tolist())
    # excel_add('test.xlsx','sheet2',['title3','title4'],[[31,32],[41,42]])

    # app.run(debug=True)

    #
    url = f"https://tsanghi.com/api/fin/stock/XSHG/income/statement/yearly?token=2655c55ebbec41ae9458417418e6d122&ticker=600276"
    print("tsinghi")
    print(requests.get(url).json())
    print("tsinghi")

    while True:
        schedule.run_pending()
        time.sleep(1)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
